//导入router的路由模式
import { createRouter, createWebHistory } from 'vue-router'
//导入进度条组件
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
//引入整体布局Layout
import Layout from '@/layout/Layout'
//import jwt from 'jsonwebtoken'
import axios from 'axios';
import common from "@/views/common/Config";


//路由规则
const routes = [
  {
    path: '/',
    redirect: '/cluster/resource'
  },
  // {
  //   path: '/test', //url路径
  //   component: () =>import('@/views/test1/Test1.vue'),  //导入视图组件,
  //   meta: {title: "测试页"} //meta原信息
  // },
  {
    path: '/login', //url路径
    component: () =>import('@/views/login/Login.vue'),  //导入视图组件,
    meta: {title: "登录"} //meta原信息
  },
  // {
  //   path: '/layout', //url路径
  //   component: () =>import('@/layout/Layout.vue'),  //导入视图组件,
  //   meta: {title: "整体布局"} //meta原信息
  // },
  {
    path: '/home', //url路径
    component: Layout,  //导入父组件,
    children: [
      {
        path: '/home',
        name: '概要',
        icon: 'odometer',
        meta: {title: "概要"},
        component: () => import("@/views/k8s-ui/home/Home.vue") //导入子组件
      },
    ]
  },
  // {
  //   path: '/git_code', //url路径
  //   component: Layout,  //导入父组件,
  //   children: [
  //     {
  //       path: '/git_code/git',
  //       name: '代码库',
  //       icon: 'odometer',
  //       meta: {title: "代码库"},
  //       component: () => import("@/views/git_code/git")
  //     }
  //   ]
  // },
  {
    path: "/cmdb",
    name: "CMDB",
    component: Layout,
    icon: "home-filled",
    meta: {title: "CMDB"},
    children: [
      {
        path: "/cmdb/servergroup",
        name: "服务器组",
        icon: "el-icon-s-data",
        meta: {title: "Servergroup"},
        component: () => import("@/views/cmdb/servergroup/Servergroup")
      },
      {
        path: "/cmdb/server",
        name: "服务器",
        icon: "el-icon-s-data",
        meta: {title: "Servers"},
        component: () => import("@/views/cmdb/servers/Servers")
      },
      {
        path: "/cmdb/credential",
        name: "凭据管理",
        icon: "el-icon-s-data",
        meta: {title: "credentials"},
        component: () => import("@/views/cmdb/credential/credential")
      },
      {
        path: "/cmdb/terminal",
        name: "远程Xshell",
        icon: "el-icon-s-data",
        meta: {title: "Xshell"},
        component: () => import("@/views/cmdb/Terminal/index")
      },
    ]
  },

  {
    path: "/devops",
    name: "发布系统",
    component: Layout,
    icon: "home-filled",
    meta: {title: "发布系统"},
    children: [
      {
        path: "/devops/git_code",
        name: "代码管理",
        icon: "el-icon-s-data",
        meta: {title: "Servergroup"},
        component: () => import("@/views/git_code/git") //代码库管理
      },
      {
        path: "/devops/project_management",
        name: "项目管理",
        icon: "el-icon-s-data",
        meta: {title: "Servers"},
        component: () => import("@/views/release_server/project/project_management")//临时未开发
      },
      // {
      //   path: "/devops/server",
      //   name: "发布项目订单",
      //   icon: "el-icon-s-data",
      //   meta: {title: "Servers"},
      //   component: () => import("@/views/release_server/project_order/order")//临时未开发
      // },
      {
        path: "/devops/pipleline",
        name: "流水线",
        icon: "el-icon-s-data",
        meta: {title: "pipleline"},
        component: () => import("@/views/release_server/pipleline/Piplelinejob")//流水线
      },
      {
        path: "/devops/tooles",
        name: "中间件配置",
        icon: "el-icon-s-data",
        meta: {title: "Xshell"},
        component: () => import("@/views/release_server/install_tools/Tooles")//临时未开发
      },
    ]
  },

  {
    path: "/cluster",
    name: "K8S资源管理",
    component: Layout,
    icon: "home-filled",
    meta: {title: "K8S资源管理"},
    children: [
      {
        path: '/cluster/install_k8s',
        name: '安装k8s集群',
        icon: 'el-icon-s-data',
        meta: {title: 'install_k8s'},
        component: () => import("@/views/k8s-ui/install_k8s/install_k8s.vue")
      },
      {
        path: '/cluster/resource',
        name: '集群选择',
        icon: 'el-icon-s-data',
        meta: {title: 'resource'},
        component: () => import("@/views/k8s-ui/resource/Resource.vue")
      },
      {
        path: "/cluster/node",
        name: "Node",
        icon: "el-icon-s-data",
        meta: {title: "Node"},
        component: () => import("@/views/k8s-ui/node/Node.vue")
      },
      {
        path: "/cluster/namespace",
        name: "Namespace",
        icon: "el-icon-document-add",
        meta: {title: "Namespace"},
        component: () => import("@/views/k8s-ui/namespace/Namespace.vue")
      },


    ]
  },
  // {
  //   path: '/workflow', //url路径
  //   component: Layout,  //导入父组件,
  //   children: [
  //     {
  //       path: '/workflow',
  //       name: '工作流',
  //       icon: 'VideoPlay',
  //       meta: {title: "工作流"},
  //       component: () => import("@/views/workflow/Workflow.vue") //导入子组件
  //     }
  //   ]
  // },
  {
    path: '/workload',
    name: '工作负载',
    component: Layout,
    icon: "menu",
    meta: {title: '工作负载'},
    children: [
      {
        path: '/workload/deployment',
        name: 'Deployment',
        icon: 'el-icon-s-data',
        meta: {title: 'Deployment'},
        component: () => import("@/views/k8s-ui/deployment/Deployment.vue")
      },
      {
        path: '/workload/pod',
        name: 'Pod',
        icon: 'el-icon-document-data',
        meta: {title: 'Pod'},
        component: () => import("@/views/k8s-ui/pod/Pod.vue")
      },
      {
        path: '/workload/daemonset',
        name: 'DaemonSet',
        icon: 'el-icon-document-data',
        meta: {title: 'DaemonSet'},
        component: () => import("@/views/k8s-ui/daemonset/Daemonset.vue")
      },
      {
        path: "/workload/statefulset",
        name: "StatefulSet",
        icon: "el-icon-document-add",
        meta: {title: "StatefulSet"},
        component: () => import("@/views/k8s-ui/statefulset/StatefulSet.vue")
      }
     ]
   },
  {
    path: "/loadbalance",
    name: "负载均衡",
    component: Layout,
    icon: "files",
    meta: {title: "负载均衡"},
    children: [
      {
        path: "/loadbalance/service",
        name: "Service",
        icon: "el-icon-s-data",
        meta: {title: "Service"},
        component: () => import("@/views/k8s-ui/service/Service.vue")
      },
      {
        path: "/loadbalance/ingress",
        name: "Ingress",
        icon: "el-icon-document-add",
        meta: {title: "Ingress"},
        component: () => import("@/views/k8s-ui/ingress/Ingress.vue")
      },
      {
        path: "/cluster/storageclasses",
        name: "storageclasses",
        icon: "el-icon-document-add",
        meta: {title: "Namespace"},
        component: () => import("@/views/k8s-ui/StorageClasses/StorageClasses.vue")
      },
    ]
  },
  {
    path: "/storage",
    name: "存储与配置",
    component: Layout,
    icon: "tickets",
    meta: {title: "存储与配置"},
    children: [
      {
        path: "/storage/configmap",
        name: "Configmap",
        icon: "el-icon-document-add",
        meta: {title: "Configmap"},
        component: () => import("@/views/k8s-ui/configmap/ConfigMap.vue")
      },
      {
        path: "/storage/secret",
        name: "Secret",
        icon: "el-icon-document-add",
        meta: {title: "Secret"},
        component: () => import("@/views/k8s-ui/secret/Secret.vue")
      },
      {
        path: "/cluster/persistentvolume",
        name: "PersistentVolume",
        icon: "el-icon-document-add",
        meta: {title: "PersistemtVolume"},
        component: () => import("@/views/k8s-ui/pv/Pv.vue")
      },
      {
        path: "/cluster/persistentvolumeclaims",
        name: "Persistentvolumeclaims",
        icon: "el-icon-document-add",
        meta: {title: "Persistentvolumeclaims"},
        component: () => import("@/views/k8s-ui/pvc/Pvc.vue")
      }
    ]
  },
  {
    path: '/404', //url路径
    component: () =>import('@/views/common/404.vue'),  //导入视图组件,
    meta: {title: "404"} //meta原信息
  },
  //未匹配到上面路由的页面直接跳转到404
  {
    path: '/:pathMatch(.*)',
    redirect: '/404'
  }
]



//创建路由实例
const router = createRouter({
//hash模式：createWebHashHistory
//history模式：createWebHistory
  history: createWebHistory(),
  routes
})

//递增进度条，这将获取当前状态值并添加0.2直到状态为0.994
NProgress.inc(100)
//easing 动画字符串
//speed 动画速度
//showSpinner 进度环显示隐藏
NProgress.configure({ easing: 'ease', speed: 600, showSpinner: false })
//router.beforeEach（）一般用来做一些进入页面的限制。比如没有登录，就不能进入某些
//页面，只有登录了之后才有权限查看某些页面。。。说白了就是路由拦截。
//to 要去到某个页面的属性
//from 从哪个页面来的属性
//next 处理路由跳转及放行
router.beforeEach((to, from, next) => {
// 启动进度条
  NProgress.start()
// 设置头部
  if (to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = "Kubernetes"
  }


  //token验证
  // if (to.path === '/login' ) {
  //   next();
  // } else {
  //   //next();
  //   const token = localStorage.getItem('token');
  //   if (!token || token === 'nil' || token === 'undefined' || token === "账号密码错误") {
  //     next({ path: '/login', query: { redirect: to.fullPath } });
  //   } else {
  //     // Validate token here
  //
  //     axios.get(common.serverList, {
  //       headers: {
  //         Authorization: `${localStorage.getItem('token')}`
  //       }
  //     }).then(() => {
  //       next();
  //     }).catch(error => {
  //       console.log(error.response)
  //       //if ( error.response.data.msg === "TokenExpired" || error.response.data.msg === "TokenNotValidYet" || error.response.data.msg === "TokenInvalid" || error.response.data.msg === "TokenMalformed") {
  //       if ( error.response.data.msg !== "" ) {
  //         next({ path: '/login', query: { redirect: to.fullPath } });
  //       } else {
  //         next();
  //       }
  //     });
  //   }
  // }

  // 路由守卫逻辑修复
  if (to.path === '/login') {
    next();
  } else {
    const token = localStorage.getItem('token');

    // 1. 检查 token 是否存在
    if (!token) { // 仅需判断是否为 null 或空字符串
      next({ path: '/login', query: { redirect: to.fullPath } });
      return;
    }

    // 2. 验证 token（关键修复：添加 Bearer 前缀）
    axios.get(common.serverList, {
      headers: {
        // 正确格式：Bearer + 空格 + token
        Authorization: `Bearer ${token}`
      }
    }).then(() => {
      // token 有效，放行
      next();
    }).catch(error => {
      // 3. 完善错误处理
      console.log('token 验证失败:', error);

      // 处理网络错误（无 response 的情况）
      if (!error.response) {
        alert('网络错误，请检查连接');
        return;
      }

      // 处理 token 相关错误（过期、无效等）
      const errorMsg = error.response.data?.msg || '';
      const invalidTokenMsgs = [
        "TokenExpired",
        "TokenNotValidYet",
        "TokenInvalid",
        "TokenMalformed",
        "token格式错误" // 包含后端返回的格式错误提示
      ];

      // 如果是 token 相关错误，跳转到登录页
      if (invalidTokenMsgs.includes(errorMsg)) {
        localStorage.removeItem('token'); // 清除无效 token
        next({ path: '/login', query: { redirect: to.fullPath } });
      } else {
        // 其他错误（如服务器内部错误），可根据需求处理
        next(); // 或提示错误后跳转
      }
    });
  }

})

router.afterEach(() => {
// 关闭进度条
  NProgress.done()
})

//抛出路由实例，在main.js中引用
export default router